from users.models import EmailVerifyRecord
from django.core.mail import send_mail
import random
import string


def random_str(randomlength=8):
    """随机生成长度为8的字符串"""
    """
    string.ascii_letters：生成a-z,A-Z
    string.digits：生成0-9的字符串
    """
    chars = string.ascii_letters + string.digits    # 生成a-z,A-Z,0-9的字符串

    strcode = ''.join(random.sample(chars, randomlength))

    return strcode


# 向数据库中写入验证码，两个参数，邮箱和验证码类型，默认是register
def send_register_email(email, send_type='register'):
    email_record = EmailVerifyRecord()
    code = random_str()
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()
    # 判断是不是注册操作
    if send_type == 'register':
        email_title = '博客注册激活链接'
        email_body = '请点击以下链接激活账号：http://127.0.0.1:8000/users/active/{0}'.format(code)
        send_status = send_mail(email_title, email_body, '18829025600@163.com', [email])
        if send_status:
            pass

    elif send_type == 'forget':
        email_title = '博客找回密码链接'
        email_body = '请点击以下链接修改账号密码：http://127.0.0.1:8000/users/forget_pwd_url/{0}'.format(code)
        send_status = send_mail(email_title, email_body, '18829025600@163.com', [email])
        if send_status:
            pass

